package org.nanyuan.forum.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.nanyuan.forum.common.AppResult;
import org.nanyuan.forum.common.ResultCode;
import org.nanyuan.forum.config.AppConfig;
import org.nanyuan.forum.model.Article;
import org.nanyuan.forum.model.ArticleReply;
import org.nanyuan.forum.model.User;
import org.nanyuan.forum.service.IArticleReplyService;
import org.nanyuan.forum.service.IArticleService;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IArticleReplyService articleReplyService;

    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @RequestParam("articleId") @NonNull Long articleId,
                            @RequestParam("content") @NonNull String content) {

        //获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断当前用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //获取帖子信息
        Article article = articleService.selectById(articleId);
        //对帖子进行校验
        if (article == null || article.getDeleteFlag() == 1) {
            //已删除或不存在
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //对帖子状态进行校验
        if (article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED);
        }
        //构造回复的对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);   //回复的文章id
        articleReply.setPostUserId(user.getId());  //回复者的id
        articleReply.setContent(content);     //回复的内容
        //写入数据库
        articleReplyService.create(articleReply);
        //返回成功信息
        return AppResult.success("回复成功");
    }

    @GetMapping("/getReplyList")
    public AppResult<List<ArticleReply>> getReplyList(@Param("articleId") @NonNull Long articleId) {

        //校验帖子是否存在
        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteFlag() == 1) {

            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //调用service，获取结果
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        //返回结果
        return AppResult.success(articleReplies);
    }
}
